/*
 * @Author: 高富强
 * @Email: 875627570@qq.com
 * @Date: 2020-06-10 14:06:42
 * @Last Modified by: 高富强
 * @Last Modified time: 2020-06-09 16:13:14
 * @Description: 班级页面 - 班级弹窗选择页
 */


import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_code_framework/base/base_widget.dart';
import 'package:flutter_code_framework/model_data/book/book.dart';

import 'package:flutter_code_framework/model_data/subject/subject.dart';
import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';
import 'package:shared_preferences/shared_preferences.dart';

//使用方法：
// new BookListPopPage( callback: selectbookcallback)
// //调用公共教材选择弹窗回调函数
//  GetSelectedBook selectbookcallback(String bookId,String bookName，String periodId,String subjectId) {
//    print("回调bookName:" + bookName.toString());
//    print("回调bookId:" + bookId.toString());
//  }

typedef void GetSelectedBook(String selBookId,String selBookName,String periodId,String subjectId);
class BookListPopPage extends BaseWidget {
  String reBookId;
  String reBookName;
  String rePeriodId;
  String reSubjectId;
  GetSelectedBook callback;
  BookListPopPage({Key key,this.reBookId,this.reBookName,this.rePeriodId,this.reSubjectId, @required this.callback}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> getState() {
    return _BookListPopPageState(reBookId:this.reBookId,reBookName:this.reBookName,rePeriodId:this.rePeriodId,reSubjectId:this.reSubjectId);
  }
}

class _BookListPopPageState extends BaseWidgetState<BookListPopPage> {
  String reBookId;
  String reBookName;
  String rePeriodId;
  String reSubjectId;
  _BookListPopPageState({Key key,this.reBookId,this.reBookName,this.rePeriodId,this.reSubjectId}) {  }
  //学科集合
  List<Object> subjectList = [null];
  //教材集合
  List<Object> bookList = [null];
  ScrollController _controller = ScrollController();
  String subjectIds='';
  String selSubjectId='';
  String selPeriodId='';
  String selBookId='';
  String selBookName='';

  int countSubjectFlag=1;
  int countBookFlag=1;
  bool clickFlag=false;

  FixedExtentScrollController periodScrollController =FixedExtentScrollController(initialItem: 1);
  Map<String, Object> periodPickerValue = { "id":-1, "name":""};
  List<dynamic> periodList = [];
  setPeriodPickerValue(int index) async {
    setState(()  {
      periodPickerValue = periodList[index];
      print("选中PName："+periodPickerValue['name']+',id:'+periodPickerValue['id'].toString());
      selPeriodId=periodPickerValue['id'].toString();
      print("选中periodId："+selPeriodId);
      periodPickerValue = periodList.firstWhere(
              (element) => element['id'] ==int.parse(selPeriodId), orElse: () {
        return periodList[0];
      });
      periodScrollController = FixedExtentScrollController(
          initialItem: periodList.indexOf(periodPickerValue));
      subjectList = [null];
      selSubjectId='';
      bookList = [null];
      countBookFlag=0;
    });
    loadMoreSubjectData();
  }

  Widget buildSubjectGrid() {
    List<Widget> tiles = [];//先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget

    Color _buttonColor= Theme.of(context).primaryTextTheme.button.color;
    //Color.fromRGBO(255,255,255,1);
    Color _textColor=Theme.of(context).primaryTextTheme.headline6.color;
    //Color.fromRGBO(124, 124, 124, 1);
    Color _buttonActiveColor =    Theme.of(context).primaryColor;
    //Color.fromRGBO(57, 135, 110, 1);
    Color _textActiveColor =  Theme.of(context).primaryTextTheme.button.color;
    //Color.fromRGBO(255, 255, 255, 1);
    if(subjectList.length>1) {
      for (var item in subjectList) {
        Subject model = item;
       // print(model.name);
        if(model!=null&&model.name!=null) {
          tiles.add(
            Container(
              color: Theme.of(context).backgroundColor,
              height: 32,
              child: Container(
                decoration: new BoxDecoration(
                  //color: Theme.of(context).primaryTextTheme.headline5.color,
                  borderRadius: BorderRadius.all(Radius.circular(35)),
                  border: Border.all(
                      width: 1,
                      color: Theme.of(context).primaryTextTheme.subtitle2.color.withOpacity(0.7)),
                ),
                child:
                new FlatButton(
                  //minWidth: 72,
                  color: selSubjectId==model.id.toString()?_buttonActiveColor:_buttonColor,//Colors.green
                  textColor:selSubjectId==model.id.toString()?_textActiveColor: _textColor,
                  child: new Text('${model.name.length>18?model.name.substring(0,18)+'...':model.name}',
                      style: TextStyle(color:selSubjectId==model.id.toString()?_textActiveColor: _textColor,fontSize: 16.0)),
                  onPressed: () {
                    setState(() {
                      selSubjectId=model.id.toString();
                    });
                    bookList = [null];
                    loadMoreBookData();
                    /*showNormalToast(
                                       '班级id:${model.id}',
                                     );*/
                  },
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(35) //设置圆角
                  ),
                ),
              ),
            ),
          );
        }
      }
    }
    content = new
    Padding(
        padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
        child: Wrap(
        spacing: 14,
        runSpacing: 12,
        children: tiles,
        ),
    );
//    Wrap(
//        //runSpacing:6,
//        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
//      //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
//    );
    return content;
  }


  @override
  Widget buildWidget(BuildContext context) {



    if(countSubjectFlag>1) {
      return Container(
          height:getMainWidgetHeight(),
          margin:EdgeInsets.only(left:24,right:24),
          child:  ListView(

            children: <Widget>[

              SizedBox(height: 26),
              Row(

                children: <Widget>[
                  Container(
                    //margin: EdgeInsets.only(left:24.0),
                    child:
                    Text('选择教材',style: TextStyle(
                        color: Theme.of(context).primaryTextTheme.headline2.color
                        //Colors.black
                        ,
                        fontSize: 28.0)),
                  ),
                  Container(
                    //margin: EdgeInsets.only(left:0.0),
                    child:
                    Align(
                        alignment: Alignment.centerLeft,
                        child:Container(margin: EdgeInsets.only(left:10.0),
                          child:Icon(SFSymbols.book_circle_fill,size: 24,color: Theme.of(context).primaryColor ,),
                        )),
                  )
                ],
              ),
              SizedBox(height: 16),
              Row(children: <Widget>[
                Container(
                  child:
                  Text('请根据学科选择您当前使用的教材',style: TextStyle(
                      color:Theme.of(context).primaryTextTheme.headline2.color.withOpacity(0.7),

                      fontSize: 16.0)),
                )
              ],
              ),
              SizedBox(height: 21),
              Container(
                child: buildSubjectGrid(),),
              SizedBox(height: 11),
              Container(
            child:
              getBookListView(context),
          ),
              SizedBox(height: 20),
            ],)
      );
    }
    else
    {
      return Center(
        child: CircularProgressIndicator(),
      );
    }


  }

  Widget getBookListView(BuildContext context) {
    Widget mainWidget;
    //print('countBookFlag:'+countBookFlag.toString());
    //默认空数据状态
    if ( bookList == [null]||bookList.length==1) {
      if(countBookFlag==1) {
        mainWidget = Center(
          child: CircularProgressIndicator(),
        );
      }
      else{
        mainWidget = Center(
          child:
          Column(children: <Widget>[
            SizedBox(height: 20),
            Text('当前学段学科下暂无教材'),
          ],)

        );
      }
    } else {
      // RefreshIndicator为ListView增加了下拉刷新能力，onRefresh参数传入一个方法，在下拉刷新时调用
      mainWidget =  ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        scrollDirection: Axis.vertical,
        itemCount: bookList.length,
        itemBuilder: (bcontext, index) =>
            _renderClassRow(index),
        controller: _controller,
        // physics: AlwaysScrollableScrollPhysics(),

      );
    }
    return mainWidget;
  }

  //初始化项目结构
  Widget _renderClassRow(int index) {
    Widget itemWidget;
    if (bookList[index] == null) {
      if (bookList.length - 1 == pageNum * curPage) {
        //加载更多
        itemWidget = Container(
            padding: const EdgeInsets.all(16.0),
            alignment: Alignment.center,
            child: SizedBox(
                width: 24.0,
                height: 24.0,
                child: CircularProgressIndicator(strokeWidth: 2.0)));
      } else {
        //到头了
        /*return Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(16.0),
            child: Text(
              "----我是有底线的-----",
              style: TextStyle(color: Colors.grey),
            ));*/
      }
    } else {
      itemWidget = Row(
        children: <Widget>[
          Expanded(
            child: getItemWidet(index),
          ),
        ],
      );
    }

    return InkWell(
      child: Padding(
        padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
        child: itemWidget,
      ),
      onTap: () {
        listViewItemFunction(index);
      },
    );
  }
  @override
  Widget getItemWidet(int index) {
    Book model = bookList[index];
    String bookId=model.id.toString();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Row(children: <Widget>[
          Expanded(flex: 7,child:
          Container(
              //height: 100,
              color:
              Theme.of(context).backgroundColor
              //Colors.white
              ,
              child: Column(children: <Widget>[
                SizedBox(height: 20,),
                Row(children: <Widget>[
                  Container(
                      //height: 25,
                      width: 246,
                      color:
                       Theme.of(context).backgroundColor
                      //Colors.white
                      ,
                      child:Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                              model.name,
                              //'${model.name.length>13?model.name.substring(0,10)+'...':model.name}',
                              overflow: TextOverflow.visible,
                              softWrap:true,
                              style: TextStyle(color:Theme.of(context).primaryTextTheme.caption.color,fontSize: 18.0)
                          )
                      ))
                ],),
                SizedBox(height: 10,),
                Row(children: <Widget>[
                  Expanded(flex: 4,child:  Container(
                      height: 20,
                      color:Theme.of(context).backgroundColor
                      //Colors.white
                      ,
                      child:Align(
                          alignment: Alignment.centerLeft,
                          child: Text('${model.publishName}',style: TextStyle(color: Theme.of(context).primaryTextTheme.caption.color,fontSize: 14.0))))),
                  Expanded(flex: 3,child:  Container(
                      height: 20,
                      color:Theme.of(context).backgroundColor
                      //Colors.white
                      ,
                      child:Align(
                          alignment: Alignment.centerLeft,//七年级
                          child: Text('${model.gradeName}',style: TextStyle(color: Theme.of(context).primaryTextTheme.caption.color,fontSize: 14.0))))),
                ],),
                SizedBox(height: 25,),
              ],)),
          ),
          Expanded(flex: 1,child: Container(

            color:Theme.of(context).backgroundColor
            //Colors.white
            ,
          ),),
          Expanded(flex: 1,child: Container(
            color: Theme.of(context).backgroundColor
            //Colors.white
            ,
            child: selBookId==bookId?Icon(SFSymbols.checkmark_seal_fill,size: 28,color: Theme.of(context).accentColor,):null,
          ),),
        ],),

        Divider(
          height: 1,
          color:  Theme.of(context).primaryTextTheme.caption.color
          //Color.fromRGBO(118,118,118,1)
          ,
        ),
      ],
    );
  }
  @override
  void initState() {
    super.initState();
    setState(() {
      selBookId=this.reBookId;
      selBookName=this.reBookName;
      selPeriodId=this.rePeriodId;
      selSubjectId=this.reSubjectId;
    });
    //初始化基础数据
    initBaseData();
    loadMoreSubjectData();
    loadMoreBookData();
  }
//加载列表数据
  loadMoreSubjectData() async {
    subjectList.clear();
    String periodId='';
    if(selPeriodId!='')
    {
        periodId=selPeriodId;
    }
    else {
      periodId = G.user.data.periodId.toString();
    }
    //学科
    var _subject = await G.req.subjectData.getList(
        schoolId: G.user.data.schoolId.toString(),
        periodId: periodId);
    if (_subject.data['subjectList'].length > 0) {
      setState(() {
        subjectList.addAll(_subject.data["subjectList"].map((e) => Subject.fromJson(e)).toList());
        countSubjectFlag++;
        subjectIds = '|'+G.user.data.subjectId.toString()+',';
      });
    }
  }
    loadMoreBookData() async {
    if(selSubjectId==''||selSubjectId==null)
      {
        selSubjectId=G.user.data.subjectId.toString();
      }
    String periodId='';
    if(selPeriodId!='')
    {
      periodId=selPeriodId;
    }
    else {
      periodId = G.user.data.periodId.toString();
    }

    var _book = await G.req.bookData.getBookList(
      schoolId: G.user.data.schoolId.toString(),
      periodId:periodId,
      subjectId: selSubjectId,//G.user.data.subjectId
      gradeId: G.user.data.gradeId.toString(),
    );

      setState(() {
        if (_book.data['bookList'].length > 0) {
          bookList.addAll(_book.data["bookList"].map((e) => Book.fromJson(e)).toList());
          countBookFlag=1;
        }else {
          countBookFlag=0;
        }
      });

  }


  initPeroidDataList() async {
    //学段
    var _period = await G.req.periodData.getList();
    if (_period.data['periodList'].length > 0) {
      setState(() {
        periodList = _period.data['periodList'];
      });
    }
  }
  initBaseData() async {
    await initPeroidDataList();

    print('初始化时periodId:'+selPeriodId);
    //加载数据
    if (periodList != null && periodList.length > 0) {
      setState(() {
        periodPickerValue = periodList.firstWhere(
                (element) => element['id'] ==int.parse(selPeriodId), orElse: () {
          return periodList[0];
        });
        periodScrollController = FixedExtentScrollController(
            initialItem: periodList.indexOf(periodPickerValue));
      });
    }

  }
  @override
  void onCreate() {
    // log("onCreate");
    setAppTopNavBarVisible(true);
    setTopNavLeftIcon(SFSymbols.xmark);
  }

  @override
  void onPause() {
    // log('onPause');
  }

  @override
  void onResume() {
    // log("onResume");
  }
  @override
  void dispose(){
    widget.callback(selBookId,selBookName,selPeriodId,selSubjectId);
    super.dispose();
  }
  @override
  ///ListView Item 单击事件
  void listViewItemFunction(int index)
  {
    Book model = bookList[index];
    /*showNormalToast(
      '选中的教材Id：'+model.id.toString(),
    );*/
//    G.user.data.bookId=model.id;
//    G.user.data.bookName=model.name;
    setState(() {
      selBookId=model.id.toString();
      selBookName=model.name.toString();
    });
    //跳转
    Future.delayed(Duration( milliseconds: 200), (){
      Navigator.of(context).pop();
      print('延时200毫秒执行');
    });
  }

  @override
  Widget getTopNavRightWidget(BuildContext _contextBaseFunction) {
    //授课学段
    Widget periodInfo =Container(
      color: Colors.white,
      child:Text(periodPickerValue["name"], style: TextStyle( color:Theme.of(context).primaryColor, fontSize: 14)),
    );
    return Container(
        height: 20,
        child:
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Align(
            alignment: Alignment.centerRight,
            child:
            showPickerList(context, periodScrollController, periodList,periodInfo, setPeriodPickerValue)),

            Padding(
            padding: EdgeInsets.only(left:3),child:Icon(SFSymbols.arrow_right_arrow_left_circle,size: 14,
              color:Theme.of(context).primaryColor
              ,
            ),),
          ],)
    );
  }
}

